package com.fqgj.sentry.common.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by ykpbean kangping.ying@yuntu-inc.com
 *
 * @description
 * @create 2017-07-14 上午9:59
 */


public class AESUtils {
    public static String CIPHER_ALGORITHM = "AES";
    private static final String KEY = "8ab1de95-cc8b-4ff1-9df0-cf6b579d457e";

    public AESUtils() {
    }

    public static Key getKey(String strKey) {
        try {
            if(strKey == null) {
                strKey = "";
            }

            KeyGenerator _generator = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN");
            secureRandom.setSeed(strKey.getBytes());
            _generator.init(128, secureRandom);
            return _generator.generateKey();
        } catch (Exception var3) {
            throw new RuntimeException(" 初始化密钥出现异常 ");
        }
    }

    public static String encrypt(String content) {
        try {
            SecureRandom sr = new SecureRandom();
            Key secureKey = getKey("8ab1de95-cc8b-4ff1-9df0-cf6b579d457e");
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(1, secureKey, sr);
            byte[] bt = cipher.doFinal(content.getBytes());
            String strS = (new BASE64Encoder()).encode(bt);
            strS = replaceBlank(strS);
            return strS;
        } catch (Exception var6) {
            var6.printStackTrace();
            return null;
        }
    }

    public static String decrypt(String content) {
        try {
            content = replaceBlank(content);
            SecureRandom sr = new SecureRandom();
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            Key secureKey = getKey("8ab1de95-cc8b-4ff1-9df0-cf6b579d457e");
            cipher.init(2, secureKey, sr);
            byte[] res = (new BASE64Decoder()).decodeBuffer(content);
            res = cipher.doFinal(res);
            return new String(res);
        } catch (Exception var5) {
            var5.printStackTrace();
            return null;
        }
    }

    private static String replaceBlank(String str) {
        String dest = "";
        if(str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
            dest = dest.replaceAll("\"", "");
        }

        return dest;
    }
}
